﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;

namespace Utils
{
    /// <summary>
    /// 验证工具
    /// </summary>
    public static class ValidatorHelper
    {

        #region 正则验证

        public const string Mobile = @"^([+][0-9]{2,3}[-]?)?(1[1-9][0-9])\d{8}$";

        public const string Phone = @"(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$";

        #endregion

        #region 字符串验证
        /// <summary>
        /// 检查是否为空字符串,并移除首尾空字符
        /// </summary>
        /// <param name="str">待检测字符</param>
        /// <returns>true-是空字符串，false:非空字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        /// string str="";
        /// bool ret=str.IsNullOrEmptyAndTrim();    //返回 true
        /// 
        /// str="   ";
        /// ret=str.IsNullOrEmptyAndTrim();    //返回 true
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsNullOrEmpty(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return true;
            return false;
        }
        /// <summary>
        /// 检查是否为空字符串,并移除首尾空字符
        /// </summary>
        /// <param name="str">待检测字符</param>
        /// <returns>true-是空字符串，false:非空字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        /// string str="";
        /// bool ret=str.IsNullOrWhiteSpace();    //返回 true
        /// 
        /// str="   ";
        /// ret=str.IsNullOrWhiteSpace();    //返回 true
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsNullOrWhiteSpace(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return true;
            str = str.Trim();
            if (string.IsNullOrEmpty(str))
                return true;
            return false;
        }

        /// <summary>
        /// 正则表达式匹配
        /// </summary>
        /// <param name="str">待检查字符串</param>
        /// <param name="pattern">表达式</param>
        /// <returns>是否匹配成功</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        /// 
        /// string str="123";
        /// string pattern="^\\d+$";
        /// 
        /// bool isMatch=str.IsMatch(pattern);  //返回 True
        /// 
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsMatch(this string str, string pattern)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            if (string.IsNullOrEmpty(pattern))
                throw new ArgumentNullException("pattern");
            return Regex.IsMatch(str, pattern, RegexOptions.IgnoreCase);
        }


        /// <summary>
        /// 是否为有效的手机号码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsMobile(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            return Regex.IsMatch(str, Mobile);
        }

        /// <summary>
        /// 是否为有效电话号码，支持格式8位和7位无区号电话号码和有区号电话号码
        /// 如：86711234,057186711234,0571-86711234
        /// </summary>
        /// <param name="str">待验证字符串</param>
        /// <returns>是否验证通过</returns>
        public static bool IsPhone(this string str)
        {
            if (string.IsNullOrEmpty(str) || str.Length < 7 || str.Length > 13)
            {
                return false;
            }
            bool isMatched = Regex.IsMatch(str, Phone);
            if (isMatched)
            {
                if (!str.Contains("-") && str.Length > 12)
                {
                    return false;
                }
            }
            return isMatched;
        }

        /// <summary>
        /// 是否为ip字符串
        /// </summary>
        /// <param name="ip">ip字符串</param>
        /// <returns>是否验证通过</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     
        ///     string ip="218.218.218.218";
        ///     bool ret=ip.IsIP(); //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsIP(this string ip)
        {
            string pattrn = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
            return Regex.IsMatch(ip, pattrn);
        }

        /// <summary>
        /// 是否为合法的Email地址
        /// </summary>
        /// <param name="email">待验证Email</param>
        /// <returns>是否验证通过</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     string email="test@g.cn";
        ///     bool ret=email.IsEmail();   //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsEmail(this string email)
        {
            return Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }


        /// <summary>
        /// 是否为正确的Url(http/https/ftp)
        /// </summary>
        /// <param name="strUrl">要验证的Url</param>
        /// <returns>判断结果</returns> 
        public static bool IsUrl(this string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }

        /// <summary>
        /// 是否是否为日期格式
        /// </summary>
        /// <param name="str">待验证字符串</param>
        /// <returns>是否验证通过</returns> 
        public static bool IsDateTime(this string str)
        {
            return DateTime.TryParse(str, out _);
        }

        /// <summary>
        /// 是否都为中文
        /// </summary>
        /// <param name="str">待验证字符串</param>
        /// <returns>是否验证通过</returns> 
        public static bool IsChinese(this string str)
        {
            return str != null && Regex.IsMatch(str, "^[\u4e00-\u9fa5]*$");
        }

        /// <summary>
        /// 是否为有效的身份证证
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsIDCard(this string str)
        {
            if (str == null) return false;
            if (str.Length == 15) return CheckIDCard15(str);
            if (str.Length == 18) return CheckIDCard18(str);
            return false;
        }

        public static bool IsBankCardNo(this string no)
        {
            //第一步：从右边第1个数字开始每隔一位乘以2；
            //第二步： 把在第一步中获得的乘积的各位数字相加，然后再与原号码中未乘2的各位数字相加；
            //第三步：对于第二步求和值中个位数求10的补数，如果个位数为0则该校验码为0。
            Regex regex = new Regex(@"^\d{7,19}$");
            if (!regex.IsMatch(no)) return false;
            var temp = no;
            var temp0 = temp.ToCharArray().Reverse().ToArray();
            var sum = 0d;
            for (int i = 1, len = temp0.Length; i < len; i++)
            {
                var temp1 = Convert.ToInt16(temp0[i].ToString());
                if ((i + 1) % 2 == 0)
                {
                    temp1 *= 2;
                }
                sum += Math.Floor(temp1 / 10d) + (temp1 % 10);
            }
            var checkCode = 10 - sum % 10;
            return temp0[0].ToString() == checkCode.ToString("0");
        }
        private static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))

            {
                return false;//数字验证

            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }

            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();

            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准

        }


        private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;

        }


        /// <summary>
        ///  验证传入值是否Int32整数
        /// </summary>
        /// <param name="input">待验证值</param>
        /// <returns>是否为Int32整数</returns> 
        public static bool IsInt32(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            return int.TryParse(input, out _);
        }

        /// <summary>
        ///  验证传入值是否Int64长整数
        /// </summary>
        /// <param name="input">待验证值</param>
        /// <returns>是否为Int64长整数</returns> 
        public static bool IsInt64(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            return long.TryParse(input, out _);
        }

        /// <summary>
        /// 是否为有效的整数
        /// </summary>
        /// <param name="str">待验证字符串</param>
        /// <returns>是否为有效的整数</returns> 
        public static bool IsInteger(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            return long.TryParse(str, out _);
        }


        /// <summary>
        ///  验证传入值是否float类型值
        /// </summary> 
        /// <param name="input">待验证值</param>
        /// <returns>是否为float类型值</returns> 
        public static bool IsFloat(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            return float.TryParse(input, out _);
        }

        /// <summary>
        ///  验证传入值是否double类型值
        /// </summary>
        /// <param name="input">待验证值</param>
        /// <returns>是否为double类型值</returns>
        public static bool IsDouble(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            return double.TryParse(input, out _);
        }

        /// <summary>
        ///  验证传入值是否decimal类型值
        /// </summary>
        /// <param name="input">待验证值</param>
        /// <returns>是否为decimal类型值</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        /// string str="+123.1";
        /// bool ret=str.IsDecimal(); //True
        /// 
        /// str="-123.1";
        ///  ret=str.IsDecimal(); //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsDecimal(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return false;
            }
            return decimal.TryParse(input, out _);
        }

        /// <summary>
        /// 检测是否为有效的MAC地址
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        ///<example>
        ///<code lang="c#">
        ///<![CDATA[
        /// string str="00-50-56-C0-00-08"
        /// bool ret=str.IsMac();   //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool IsMac(this string mac)
        {
            if (string.IsNullOrEmpty(mac))
                return false;
            return Regex.IsMatch(mac, @"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$");
        }

        #endregion

        /// <summary>
        /// 是否空集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool IsEmpty<T>(this IEnumerable<T> list)
        {
            return list == null || list.Count() == 0;
        }

        public static bool IsTrue(this int number)
        {
            return number > 0;
        }


        public static bool IsNullable(this Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }


        public static bool IsConvertible(this Type type)
        {
            return typeof(IConvertible).IsAssignableFrom(type);
        }
        public static bool IsAnonymousType(this Type type)
        {
            return type.Name.Contains("AnonymousType") && Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false);
        }

        /// <summary>
        /// 超出保护
        /// </summary>
        /// <param name="value"></param>
        public static double Safe(this double value, int digits = -1)
        {
            if (!double.IsFinite(value))
            {
                return 0;
            }
            if (digits < 0)
            {
                return value;
            }
            return Math.Round(value, digits);
        }

        /// <summary>
        /// 判断是否在之间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="number"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static bool Between<T>(this T number, T begin, T end) where T : IComparable<T>
        {
            return number.CompareTo(begin) >= 0 && number.CompareTo(end) <= 0;
        }



    }
}
